package com.general.common.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.general.common.factory.ServiceFactory;
import com.general.common.security.entity.User;
import com.general.common.security.service.IUserService;
import com.general.utils.base.Opertion;
import com.general.utils.base.StringUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.util.ValueStack;

public class BaseAction extends ActionSupport implements ServletResponseAware,	ServletRequestAware, Preparable,Opertion {

	private static final long serialVersionUID = 7038570508703577185L;
	protected File file;
	private HttpServletResponse response;
	private HttpServletRequest request;

	/**
	 * 返回值栈对象
	 */
	public ValueStack getValueStack() {
		ActionContext actionContext = ActionContext.getContext();
		return actionContext.getValueStack();
	}

	/**
	 * 返回request对象
	 */
	public HttpServletRequest getRequest() {
		return this.request;
	}

	/**
	 * 返回response对象
	 */
	public HttpServletResponse getResponse() {
		return this.response;
	}

	/**
	 * 返回session对象
	 */
	public HttpSession getSession() {
		return this.request.getSession();
	}
	

	public void prepare() throws Exception {
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	
	/**
	 * 公用输出流
	 * @return
	 */
	public InputStream getInputStream(){
		try {
			ValueStack stack = getValueStack();
			stack.set("fileName", file.getName());
			return new FileInputStream(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 当前登录用户
	 * @return
	 */
	public User getCurrentUser(){
		Subject subject = SecurityUtils.getSubject();
		String userName = (String) subject.getPrincipal();
		
		if (StringUtil.isEmpty(userName)){
			return null;
		}
		
		IUserService userService = (IUserService) ServiceFactory.getBean("userService");
		return userService.getUserByUsername(userName);
	}
	
	
}
